package com.zhoulu.controller.system;

import com.zhoulu.domain.user.UserBean;
import com.zhoulu.domain.util.LayuiResult;
import com.zhoulu.enums.RoleEnum;
import com.zhoulu.service.system.SysMenuService;
import com.zhoulu.service.user.UserService;
import com.zhoulu.util.SaltUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private UserService userService;

    @GetMapping("/menu")
    public Map<String, Object> menu() {
        return sysMenuService.menu(((UserBean) SecurityUtils.getSubject().getPrincipal()).getUsername());
    }

    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest request){
        try{
            // 从SecurityUtils里边创建一个Subject
            Subject subject = SecurityUtils.getSubject();
            // 在认证提交前转呗token
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            // 执行认证登录
            try{
                subject.login(usernamePasswordToken);
            }catch (IncorrectCredentialsException ice){
                ice.printStackTrace();
                return LayuiResult.error("密码错误");
            }catch (AuthenticationException ae){
                return LayuiResult.error(ae.getMessage());
            }
            if(subject.isAuthenticated()){
                return LayuiResult.success("登录成功");
            }else{
                usernamePasswordToken.clear();
                return LayuiResult.error("登录失败");
            }
        }catch(Exception error){
            error.printStackTrace();
            return LayuiResult.error(error.getMessage());
        }
    }

    @PostMapping("/logout")
    public Object logout(){
        try{
            Subject currentSubject = SecurityUtils.getSubject();
            currentSubject.logout();
            return LayuiResult.success("注销登录成功");
        }catch(Exception error){
            error.printStackTrace();
            return LayuiResult.error(error.getMessage());
        }
    }

    @PostMapping("/updatePassword")
    public Object updatePassword(String newPassword){
        try{
            if(Strings.isNullOrEmpty(newPassword)){
                return LayuiResult.error("新密码为空，不允许修改密码！");
            }
            // 取随机盐
            String salt = SaltUtils.getSalt();
            UserBean userBean = new UserBean();
            userBean.setPassword(new SimpleHash("MD5", newPassword, salt, 2).toString());
            userBean.setSalt(salt);
            userBean.setUsername(((UserBean) SecurityUtils.getSubject().getPrincipal()).getUsername());
            userService.updatePassword(userBean);
            SecurityUtils.getSubject().logout();
            return LayuiResult.success("密码修改成功，请重新登录");
        }catch(Exception error){
            error.printStackTrace();
            return LayuiResult.error("密码修改失败：" + error.getMessage());
        }
    }

    @PostMapping("/insertUser")
    public Object insertUser(String username, String password, String roleCode){
        try{
            if(Strings.isNullOrEmpty(username)){
                return LayuiResult.error("用户名为空");
            }
            if(Strings.isNullOrEmpty(password)){
                return LayuiResult.error("密码为空");
            }
            if(Strings.isNullOrEmpty(roleCode)){
                return LayuiResult.error("请选择角色");
            }
            UserBean userBean = new UserBean();
            userBean.setUsername(username);
            UserBean queryResult = userService.queryUser(userBean);
            if(queryResult != null && !Strings.isNullOrEmpty(queryResult.getUsername())){
                return LayuiResult.error("用户名已存在");
            }
            // 取随机盐
            String salt = SaltUtils.getSalt();
            userBean.setPassword(new SimpleHash("MD5", password, salt, 2).toString());
            userBean.setSalt(salt);
            userBean.setLocked(false);
            userBean.setRoleCode(roleCode);
            userService.insertUser(userBean);
            return LayuiResult.success("注册成功");
        }catch(Exception error){
            error.printStackTrace();
            return LayuiResult.error("用户注册失败：" + error.getMessage());
        }
    }

    @PostMapping("/getLoginUserInfo")
    public Object getLoginUserInfo(){
        try{
            Map<String, Object> resultMap = Maps.newHashMap();
            UserBean userBean = (UserBean) SecurityUtils.getSubject().getPrincipal();
            if(RoleEnum.Admin.getCode().equals(userBean.getRoleCode())){
                resultMap.put("roleName", RoleEnum.Admin.getName());
            }else if(RoleEnum.Teacher.getCode().equals(userBean.getRoleCode())){
                resultMap.put("roleName", RoleEnum.Teacher.getName());
            }else{
                resultMap.put("roleName", RoleEnum.Student.getName());
            }
            resultMap.put("username", userBean.getUsername());
            return LayuiResult.success("获取成功", resultMap);
        }catch(Exception error){
            error.printStackTrace();
            return LayuiResult.error("用户注册失败：" + error.getMessage());
        }
    }
}
